package com.starbugs.wehcat.jdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class JdbcUserRepository implements UserRepository{

  private JdbcTemplate jdbcTemplate;

  public static int id = 0;

  @Autowired
  public JdbcUserRepository(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }


  @Override
  public void createTable(String tableName) {
    jdbcTemplate.execute("create table if not exists user1 (\n" +
        "  id int not null,\n" +
        "  name varchar(25) not null,\n" +
        "  age int not null\n" +
        ");");
  }

  @Override
  public int addUser(User user) {
    String sql = "insert into user1 (id, name, age, points) values (?, ?, ?, ?)";
    Object[] obj = {
        user.getId(),
        user.getName(),
        user.getAge(),
        user.getPoints()
    };
    int num = jdbcTemplate.update(sql, obj);
    System.out.println(num);
    return 1;
  }

  @Override
  public int updateUser(User user) {
    String sql = "update user1 set name=?,age=? where id = ?";
    Object[] obj = {
        user.getName(),
        user.getAge(),
        user.getId()
    };
    int num = jdbcTemplate.update(sql, obj);
    System.out.println(num);
    return 1;
  }

  @Override
  public int deleteUser(int id) {
    String sql = "delete from  user1 where id = ?";
    int num = jdbcTemplate.update(sql, id);
    System.out.println(num);
    return 1;
  }

  @Override
  public User findUserById(int id) {
    String sql = "select * from user1 where id = ?";
    RowMapper<User> maps = new BeanPropertyRowMapper<>(User.class);
    User user =  jdbcTemplate.queryForObject(sql, maps, id);
    System.out.println(user);
    return user;
  }

  @Override
  public List<User> findAll() {
    String sql = "select * from user1";
    RowMapper<User> maps = new BeanPropertyRowMapper<>(User.class);
    return  jdbcTemplate.query(sql, maps);
  }

  @Override
  public void transfer(String outUser, String inUser, int points) {
    jdbcTemplate.update("update user1 set points = points + ? where name = ?", points, inUser);

    jdbcTemplate.update("update user1 set points = points - ? where name = ?", points, outUser);
  }
}
